package com.heima.app.gateway.filter;
import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.StrUtil;
import com.heima.app.gateway.config.MyConfig;
import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;


@Component
@Slf4j
public class AuthorizeFilter implements Ordered, GlobalFilter {
    
//    拿到白名单
    @Resource
    private MyConfig myConfig;

//    单例
    private static final AntPathMatcher anPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//      先拿请求头，响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

//        拿uri 进行 和白名单进行比对
        String path = request.getURI().getPath();
        String[] noAuthPaths = this.myConfig.getNoAuthPaths();
        for (String noAuthPath : noAuthPaths) {
            if (anPathMatcher.match(noAuthPath,path)) {
//                放行
                return chain.filter(exchange);
            }
        }
//       然后判断是否含有token。
        String token = request.getHeaders().getFirst("token");

//        判断token 是否为null
        if(StrUtil.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return  response.setComplete();
        }
//        token 存在 ，然后 拿到token 的 claims
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
//            claimsBody 进行解析 判断是否有效
            int code = AppJwtUtil.verifyToken(claimsBody);
            if(code == 1 || code == 2){
                // 拦截
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return  response.setComplete();
            }
        } catch (Exception e) {
//            拦截
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return  response.setComplete();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
